﻿// 栈.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

//栈
#define S_SIZE 20

struct S
{
    //int arr[S_SIZE]; // 存储栈的元素
    int* arr;             // 指向动态数组栈
    int top;              // 栈顶的位置
    int capcity;          // 动态数组扩容的容量大小
};

// 初始化
//开辟一个容量为S_SIZE大小的动态数组
void Init(S* s)
{
    s->top = 0;
    s->capcity = S_SIZE;
    s->arr = (int*)malloc(sizeof(int) * s->capcity);
    if (s->arr == NULL)
        exit(-1);
}
// 动态顺序栈销毁
void Destroy(S* s)
{
    free(s->arr);
    s->top = 0;
    s->capcity = 0;
    s->arr = NULL;

}
// 入栈
void Push(S* s, int val)
{
    if (s->top == s->capcity)
    {
        int* arr1 = (int*)malloc(sizeof(int) * 2 * s->capcity);
        if (arr1 == NULL)
        {
            exit(-1);
        }
        memcpy(arr1, s->arr, s->capcity * sizeof(int));
        free(s->arr);
        s->arr = arr1;
        s->capcity *= 2;
    }
    s->arr[s->top] = val;
    s->top++;
}
// 出栈
void Pop(S* s)
{
    if (s->top == 0)
    {
        return;
    }
    s->top--;
}
// 获取栈顶元素
int Top(S* s)
{
    return s->arr[s->top - 1];
}
// 判满
bool Full(S* s)
{
    return s->top == s->capcity;
}
// 判空
bool Empty(S* s)
{
    return s->top == 0;
}

int main()
{
    S s;
    Init(&s);

    Push(&s, 20);
    Push(&s, 54);
    Push(&s, 23);
    Push(&s, 98);
    Push(&s, 12);
    Push(&s, 77);
    Push(&s, 10);

    while (!Empty(&s))
    {
        int val = Top(&s);
        printf("%d ", val);
        Pop(&s);
    }
    printf("\n");
}
